<template>
  <div class="top-menu">
    <div class="menu-wrap"
      v-for="(item, index) in menux"
      :key="index">
      <div v-if="!item.noMenuPage"
        class="menu">
        <div class="menu-cont"
          @click="jumpOut(item)"
          v-if="item.link">
          {{ item.name }}
        </div>
        <div class="menu-cont"
          v-else
          :class="{active: curmenu.url === item.url}"
          @click="handleClick(item)">
          {{ item.name }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { findChildUrl } from '@/utils/tool.js';
  import { mapGetters } from 'vuex';

  export default {
    data() {
      return {
        activeIndex: '1',
        curmenu: {}
      };
    },
    computed: {
      // 用mapGetters需要在store里配置getters
      ...mapGetters({ topActive: 'showTopActive', menux: 'menux' })
      // topActive() {
      //   return this.$store.state.global.showTopActive;
      // }
    },
    watch: {
      topActive(bool) {
        if (!bool) {
          this.curmenu = {};
        }
      }
    },
    created() {
      this.initActive();
    },
    methods: {
      initActive() {
        // 菜单源自处理后的menuTree
        let matched = this.$route.matched.map((item) => item.path);
        this.curmenu = this.menux.find((item) => matched.includes(item.url)) || {};
        let submenu = this.curmenu.children || [];
        this.$store.commit('global/setSubMenu', submenu);
      },
      handleClick(item) {
        this.curmenu = item;
        let submenu = item.children || [];
        this.$store.commit('global/setTopActive', true);
        this.$store.commit('global/setSubMenu', submenu);
        let childUrl = findChildUrl(item);
        console.log('childUrl from menuTree', childUrl);
        this.$router.push({ path: childUrl });
      },
      jumpOut(item) {
        window.open(item.link);
      }
    }
  };
</script>

<style lang="scss" scoped>
  .top-menu {
    width: 100%;
    white-space: nowrap;
    height: 57px;
    line-height: 57px;
    .menu-wrap {
      display: inline-block;
    }
    .menu {
      margin-right: 40px;
      font-size: 16px;
      color: #fff;
      cursor: pointer;
    }
    .menu-cont {
      padding: 0 10px;
    }
    .active {
      border-bottom: 3px solid #fff;
    }
    .el-menu {
      background-color: $--primary-color;
    }
    .el-menu--horizontal {
      border-bottom: 0px;
    }
    .el-menu-item:hover {
      background-color: $--primary-color;
    }
    .el-menu-item.is-active {
      color: #fff;
    }
  }
</style>
